from . import BaseService
from app.fmodels.user import UserFunc
from flask import abort, session
from app.errcode import errcode
from app.util.redis_client import redis_client
import jwt
from jwt import PyJWTError
from datetime import datetime, timedelta

class ServiceUser(BaseService):
	def __init__(self):
		self.screct_key = "test"

	def get_list(self):
		res = UserFunc.paginate()
		return {"data": res}

	def user_register(self, params):
		res, content = UserFunc.register(params["email"], "email", params["password"])
		if res is False:
			return {"errcode": 400, "errmsg": content}
		else:
			return {"user_id": content}

	def user_login(self, params):
		res, content = UserFunc.login(params["unique_id"], params["password"])
		if res is False:
			abort(400, {"errcode": "A002", "errmsg": errcode["A002"]})
		else:
			token = self._set_jwt_token(content["id"], content)
			res = dict(user_info=content, token=token)
			session["token"] = token
			return res

	def _set_jwt_token(self, id, user_info):
		# 用户登录成功设置token
		payload = {  # jwt设置过期时间的本质 就是在payload中 设置exp字段, 值要求为格林尼治时间
			"user_id": id,
			# 'exp': datetime.utcnow() + timedelta(seconds=30)
		}
		token = jwt.encode(payload, key=self.screct_key, algorithm='HS256')
		redis_client.set_hash_key(token, user_info)
		return token

	def match_token(self, token):
		if token is None:
			return False
		res = redis_client.get_hash_key(token)
		if res is None:
			return False
		else:
			return True

	def get_user_by_token(self, token):
		# 根据token查询redis获取用户信息
		redis_user_info = redis_client.get_hash_key(token)
		try:
			data = jwt.decode(token, key=self.screct_key, algorithms='HS256')
			return redis_user_info
		except PyJWTError as e:
			abort(400, {"errcode": "A005", "errmsg": errcode["A005"]})


service_user = ServiceUser()